package com.moon;

import io.rong.imkit.RongIM;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.sys.DemoApp;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.widget.CircleImageView;

import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ClassmateActivity extends BaseActivity {
	MyAdapter mAdapter;
	JSONArray mArrayList = new JSONArray();
	View mHeadView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_classmate);

		((TextView) findViewById(R.id.center)).setText("班级联系人");
		findViewById(R.id.left).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		listview.setVerticalScrollBarEnabled(false);
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		
		listview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) 
			{
				if(arg2 < 2) return;
				
				JSONObject item = mArrayList.getJSONObject(arg2 - 2);

				String name = item.getString("username");
				if(item.getString("alias") != null && item.getString("alias").length() != 0) name = item.getString("alias");
				
				Intent intent = new Intent(ClassmateActivity.this,PersonInfoActivity.class);
				intent.putExtra("name", name);
				intent.putExtra("userId",item.getString("id"));
				intent.putExtra("flag", 0);
				startActivity(intent);
			}
		});
		
		LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mHeadView = mInflater.inflate(R.layout.head_class, null);
		listview.addHeaderView(mHeadView);
		mHeadView.findViewById(R.id.nick).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ClassmateActivity.this,ModifyClassActivity.class);
				intent.putExtra("classId", getIntent().getStringExtra("userId"));
				startActivity(intent);
			}
		});
		
		mHeadView.findViewById(R.id.tmp0).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
			}
		});
		mHeadView.findViewById(R.id.tmp1).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
			}
		});
		
		((TextView)mHeadView.findViewById(R.id.text0)).setText(InteractActivity.mClassName);
		
		JSONArray classes = JSON.parseArray(PreferencesUtils.getString(this, "classes"));
		int size = classes.size();
		for(int i = 0; i < size; i++)
		{
			JSONObject item = classes.getJSONObject(i);
			if(item.getString("id").equals(getIntent().getStringExtra("userId")))
			{
				((TextView) mHeadView.findViewById(R.id.text2)).setText(item.getString("class_alias"));
			}
		}
		
		sendRequest();
	}
	
	public void onResume()
	{
		super.onResume();
		mAdapter.notifyDataSetChanged();
	}
	
	public void setBak(String bak)
	{
		((TextView) mHeadView.findViewById(R.id.text2)).setText(bak);
	}
	
	class MyAdapter extends BaseAdapter implements OnClickListener{
		public int getCount() {
			return mArrayList.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_classmate, null);
				
				foodHold.icon = (CircleImageView)convertView.findViewById(R.id.icon);
				foodHold.text = (TextView)convertView.findViewById(R.id.text);
				foodHold.sign = (TextView)convertView.findViewById(R.id.sign);

				foodHold.btn0 = (ImageView)convertView.findViewById(R.id.btn0);
				foodHold.btn1 = (ImageView)convertView.findViewById(R.id.btn1);
				foodHold.btn2 = (ImageView)convertView.findViewById(R.id.btn2);
				
				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}
			
			JSONObject item = mArrayList.getJSONObject(position);
			
			foodHold.sign.setVisibility(View.GONE);
			if(item.getInteger("is_teacher") == 1) foodHold.sign.setVisibility(View.VISIBLE);

			JSONObject member = ((DemoApp)getApplicationContext()).mMembers.getJSONObject(item.getString("id"));
			String name = "";
					
			if(item.getString("id").equals(PreferencesUtils.getString(ClassmateActivity.this, "userId"))) name = "我";
			else if(item.getInteger("is_teacher") == 0)
			{
				JSONArray array = item.getJSONArray("child");
				if(array != null && array.size() > 0)
				{
					JSONObject child = array.getJSONObject(0);
					String iden = child.getString("identity");
					if(iden == null) iden = "";
					name = child.getString("name") + iden;
				}
			}
			else if(member != null && member.getString("alias") != null && member.getString("alias").length() != 0) name = member.getString("alias");
			else name = item.getString("username");
			foodHold.text.setText(name);
			
			String path = item.getString("avatar_path");
			if(path != null && path.length() != 0) path = "http://120.27.129.233/ylbb/" + path;
			else path = "";
			if(item.getInteger("is_teacher") == 0)
				ImageLoaderHelper.displayImage(R.drawable.ic_family, foodHold.icon,path);
			else 
				ImageLoaderHelper.displayImage(R.drawable.ic_teacher, foodHold.icon,path);
			
			foodHold.btn0.setTag(Integer.valueOf(position));
			foodHold.btn1.setTag(Integer.valueOf(position));
			foodHold.btn2.setTag(Integer.valueOf(position));
			
			foodHold.btn0.setOnClickListener(this);
			foodHold.btn1.setOnClickListener(this);
			foodHold.btn2.setOnClickListener(this);
			
			return convertView;
		}

		public final class FoodHolder {
			public CircleImageView icon;
			public TextView text;
			public TextView sign;

			public ImageView btn0;
			public ImageView btn1;
			public ImageView btn2;
		}

		@Override
		public void onClick(View arg0) {
			int pos = (Integer)arg0.getTag();
			int viewId = arg0.getId();
			JSONObject item = mArrayList.getJSONObject(pos);
			
			switch(viewId)
			{
			case R.id.btn0:
			{
				try
				{
					Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ item.getString("telephone")));  
					startActivity(intent); 
	            }
				catch(Exception e)
				{
					ToastUtil.showToastWithAlertPic("您还没有授权");
				}
				break;
			}
			
			case R.id.btn1:
			{
				try
				{
					Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("smsto:" + item.getString("telephone")));
					startActivity(sendIntent);
				}
				catch(Exception e)
				{
					ToastUtil.showToastWithAlertPic("您还没有授权");
				}
				break;
			}
			
			case R.id.btn2:
			{
				if(item.getInteger("is_active") != 1)
				{
					ToastUtil.showToastWithAlertPic("该用户还未激活，不可使用该功能");
					return;
				}
				
				if(mArrayList.getJSONObject(pos).getString("id").equals(PreferencesUtils.getString(ClassmateActivity.this, "userId")))
				{
					ToastUtil.showToastWithAlertPic("不能跟自己聊天");
					return;
				}
				
				RongIM.getInstance().startPrivateChat(ClassmateActivity.this,
						mArrayList.getJSONObject(pos).getString("id"), 
						mArrayList.getJSONObject(pos).getString("username"));
				break;
			}
			}
		}
	}
	
	private void sendRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				mArrayList = ruser.getJSONArray("members");
				((TextView)mHeadView.findViewById(R.id.text1)).setText(mArrayList.size() + "人");
				mAdapter.notifyDataSetChanged();
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("class_id", getIntent().getStringExtra("userId"));
		params.put("id", PreferencesUtils.getString(this, "userId"));
		MgqRestClient.get("get_class_member_list", params, loginHandler);
	}
}
